/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.infnet.formularioeletronico.visao;

import br.com.infnet.formularioeletronico.dados.CursoDAO;
import br.com.infnet.formularioeletronico.dados.TurmaDAO;
import br.com.infnet.formularioeletronico.interfaces.ICursoDAO;
import br.com.infnet.formularioeletronico.interfaces.ITurmaDAO;
import br.com.infnet.formularioeletronico.modelo.Curso;
import br.com.infnet.formularioeletronico.modelo.Turma;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;
import javax.swing.*;

public class TelaTurmas extends JFrame {

    private static final long serialVersionUID = -2546263461845289454L;
    private int numberOfEntries = 0;
    private int currentEntryIndex;
    private Turma currentEntry;
    private List< Turma> results;
    private List< Curso> resultsCurso;
    private JPanel painelNavegacao;
    private JButton browseButton;
    private JLabel disciplinaLabel;
    private JTextField disciplinaTextField;
    private JLabel idLabel;
    private JTextField idTextField;
    private JTextField indexTextField;
    private JTextField maxTextField;
    private JButton proximoButton;
    private JLabel deLabel;
    private JButton anteriorButton;
    private JButton queryButton;
    private JButton loadButton;
    private JLabel queryLabel;
    private JPanel queryPanel;
    private JPanel displayPanel;
    private JTextField queryTextField;
    private JButton insertButton;
    private JLabel cursoLabel;
    private JComboBox cmbCurso;

    /**
     * Create the frame.
     */
    public TelaTurmas() {
        // create GUI
        painelNavegacao = new JPanel();
        painelNavegacao.setBounds(86, 10, 222, 23);
        anteriorButton = new JButton();
        indexTextField = new JTextField(2);
        deLabel = new JLabel();
        maxTextField = new JTextField(2);
        proximoButton = new JButton();
        displayPanel = new JPanel();
        displayPanel.setBounds(86, 43, 255, 93);
        idLabel = new JLabel();
        idLabel.setBounds(0, 11, 59, 20);
        idTextField = new JTextField(10);
        idTextField.setBounds(59, 11, 45, 20);
        disciplinaLabel = new JLabel();
        disciplinaLabel.setBounds(0, 37, 59, 20);
        disciplinaTextField = new JTextField(10);
        disciplinaTextField.setBounds(59, 37, 132, 20);
        queryPanel = new JPanel();
        queryPanel.setBounds(78, 148, 263, 50);
        queryLabel = new JLabel();
        queryTextField = new JTextField(10);
        queryButton = new JButton();
        setSize(400, 270);
        setResizable(false);

        painelNavegacao.setLayout(new BoxLayout(painelNavegacao, BoxLayout.X_AXIS));

        anteriorButton.setText(" Ant ");
        anteriorButton.setEnabled(false);
        anteriorButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        previousButtonActionPerformed(evt);
                    }
                });

        painelNavegacao.add(anteriorButton);
        painelNavegacao.add(Box.createHorizontalStrut(10));

        indexTextField.setHorizontalAlignment(JTextField.CENTER);
        indexTextField.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        indexTextFieldActionPerformed(evt);
                    }
                });

        painelNavegacao.add(indexTextField);
        painelNavegacao.add(Box.createHorizontalStrut(5));

        deLabel.setText("de");
        painelNavegacao.add(deLabel);
        painelNavegacao.add(Box.createHorizontalStrut(5));

        maxTextField.setHorizontalAlignment(JTextField.CENTER);
        maxTextField.setEditable(false);
        painelNavegacao.add(maxTextField);
        painelNavegacao.add(Box.createHorizontalStrut(5));

        proximoButton.setText(" Prox ");
        proximoButton.setEnabled(false);
        proximoButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        nextButtonActionPerformed(evt);
                    }
                });
        getContentPane().setLayout(null);

        painelNavegacao.add(proximoButton);
        getContentPane().add(painelNavegacao);
        displayPanel.setLayout(null);

        idLabel.setText("ID:");
        displayPanel.add(idLabel);

        idTextField.setEditable(false);
        displayPanel.add(idTextField);

        disciplinaLabel.setText("Disciplina:");
        displayPanel.add(disciplinaLabel);
        displayPanel.add(disciplinaTextField);
        getContentPane().add(displayPanel);

        cursoLabel = new JLabel();
        cursoLabel.setText("Curso:");
        cursoLabel.setBounds(0, 62, 59, 20);
        displayPanel.add(cursoLabel);

        cmbCurso = new JComboBox();
        cmbCurso.setBounds(59, 62, 132, 20);
        displayPanel.add(cmbCurso);

        loadButton = new JButton();
        loadButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        try {
                            loadButtonActionPerformed(evt);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                });

        loadButton.setText("Load");
        loadButton.setBounds(190, 61, 65, 23);
        displayPanel.add(loadButton);

        queryPanel.setLayout(new BoxLayout(queryPanel, BoxLayout.X_AXIS));
        queryPanel.setBorder(BorderFactory.createTitledBorder("Buscar turma pela disciplina"));
        queryLabel.setText("Disciplina:");
        queryPanel.add(Box.createHorizontalStrut(5));
        queryPanel.add(queryLabel);
        queryPanel.add(Box.createHorizontalStrut(10));
        queryPanel.add(queryTextField);
        queryPanel.add(Box.createHorizontalStrut(10));

        queryButton.setText("OK");
        queryButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        try {
                            queryButtonActionPerformed(evt);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                });

        queryPanel.add(queryButton);
        queryPanel.add(Box.createHorizontalStrut(5));
        getContentPane().add(queryPanel);
        browseButton = new JButton();
        browseButton.setBounds(86, 208, 77, 23);

        browseButton.setText("List");
        browseButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        browseButtonActionPerformed(evt);
                    }
                });

        getContentPane().add(browseButton);

        insertButton = new JButton();
        insertButton.setBounds(173, 208, 77, 23);
        insertButton.setText("Insert");
        insertButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        insertButtonActionPerformed(evt);
                    }
                });
        getContentPane().add(insertButton);

        JButton updateButton = new JButton();
        updateButton.setBounds(260, 208, 77, 23);
        updateButton.setText("Update");
        updateButton.addActionListener(
                new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        updateButtonActionPerformed(evt);
                    }
                });
        getContentPane().add(updateButton);

        setTitle("Tela de Turmas");
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public static void main(String args[]) {
        new TelaTurmas();
    }

    private void previousButtonActionPerformed(ActionEvent evt) {
        currentEntryIndex--;

        if (currentEntryIndex < 0) {
            currentEntryIndex = numberOfEntries - 1;
        }

        indexTextField.setText("" + (currentEntryIndex + 1));
        indexTextFieldActionPerformed(evt);
    }

    private void nextButtonActionPerformed(ActionEvent evt) {
        currentEntryIndex++;

        if (currentEntryIndex >= numberOfEntries) {
            currentEntryIndex = 0;
        }

        indexTextField.setText("" + (currentEntryIndex + 1));
        indexTextFieldActionPerformed(evt);
    }

    private void indexTextFieldActionPerformed(ActionEvent evt) {
        currentEntryIndex = (Integer.parseInt(indexTextField.getText()) - 1);

        if (numberOfEntries != 0 && currentEntryIndex < numberOfEntries) {
            currentEntry = results.get(currentEntryIndex);

            idTextField.setText("" + currentEntry.getId());
            disciplinaTextField.setText(currentEntry.getDisciplina());
            carregaCurso(currentEntry.getCurso());

            maxTextField.setText("" + numberOfEntries);
            indexTextField.setText("" + (currentEntryIndex + 1));
        }
    }

    private void insertButtonActionPerformed(ActionEvent evt) {
        if (validarCamposObrigatoriosInclusao()) {

            int intSeparador;

            //Objeto que representa o curso selecionado
            intSeparador = cmbCurso.getSelectedItem().toString().indexOf("-");
            int intIdcurso = Integer.parseInt(cmbCurso.getSelectedItem().toString().substring(0, intSeparador - 1));

            ICursoDAO objCursoDAO = new CursoDAO();
            Curso objCurso = objCursoDAO.obter(intIdcurso);

            ITurmaDAO objTurmaDAO = new TurmaDAO();
            long result = objTurmaDAO.incluir(new Turma(disciplinaTextField.getText(),
                    objCurso));

            if (result > 0) {
                JOptionPane.showMessageDialog(this, "Turma incluída!", "Inclusão de turma", JOptionPane.PLAIN_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Turma não incluída!", "Erro", JOptionPane.PLAIN_MESSAGE);
            }

            browseButtonActionPerformed(evt);

        }
    }

    private void updateButtonActionPerformed(ActionEvent evt) {
        if (validarCamposObrigatorios()) {

            if (idTextField.getText().length() == 0) {
                JOptionPane.showMessageDialog(this, "Selecione uma turma!", "Atualização de turma", JOptionPane.WARNING_MESSAGE);
            } else {

                int intSeparador;

                //Objeto que representa o curso selecionado
                intSeparador = cmbCurso.getSelectedItem().toString().indexOf("-");
                int intIdcurso = Integer.parseInt(cmbCurso.getSelectedItem().toString().substring(0, intSeparador - 1));

                ICursoDAO objCursoDAO = new CursoDAO();
                Curso objCurso = objCursoDAO.obter(intIdcurso);

                ITurmaDAO objTurmaDAO = new TurmaDAO();
                boolean result = objTurmaDAO.alterar(new Turma(Long.parseLong(idTextField.getText()),
                        disciplinaTextField.getText(),
                        objCurso));

                if (result) {
                    JOptionPane.showMessageDialog(this, "Turma alterada!", "Atualização de turma", JOptionPane.PLAIN_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "Turma não alterada!", "Erro", JOptionPane.PLAIN_MESSAGE);
                }

                browseButtonActionPerformed(evt);
            }

        }
    }

    private void browseButtonActionPerformed(ActionEvent evt) {
        try {
            ITurmaDAO objTurmaDAO = new TurmaDAO();
            results = objTurmaDAO.listar();
            numberOfEntries = results.size();

            if (numberOfEntries != 0) {
                currentEntryIndex = 0;
                currentEntry = results.get(currentEntryIndex);

                idTextField.setText("" + currentEntry.getId());
                disciplinaTextField.setText(currentEntry.getDisciplina());
                carregaCurso(currentEntry.getCurso());

                maxTextField.setText("" + numberOfEntries);
                indexTextField.setText("" + (currentEntryIndex + 1));

                proximoButton.setEnabled(true);
                anteriorButton.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(this, "Não há turmas cadastradas!", "Listar turmas", JOptionPane.WARNING_MESSAGE);
                idTextField.setText("");
                disciplinaTextField.setText("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadButtonActionPerformed(ActionEvent evt) throws SQLException {
        ICursoDAO objCursoDAO = new CursoDAO();
        resultsCurso = objCursoDAO.listar();
        if (resultsCurso.size() > 0) {
            carregaComboCursos(resultsCurso);
        } else {
            cmbCurso.removeAllItems();
        }
    }

    private void queryButtonActionPerformed(ActionEvent evt) throws SQLException {
        ITurmaDAO objTurmaDAO = new TurmaDAO();
        results = objTurmaDAO.listar("disciplina", queryTextField.getText().toUpperCase());
        numberOfEntries = results.size();

        if (numberOfEntries != 0) {
            currentEntryIndex = 0;
            currentEntry = results.get(currentEntryIndex);

            idTextField.setText("" + currentEntry.getId());
            disciplinaTextField.setText(currentEntry.getDisciplina());
            carregaCurso(currentEntry.getCurso());

            maxTextField.setText("" + numberOfEntries);
            indexTextField.setText("" + (currentEntryIndex + 1));

            proximoButton.setEnabled(true);
            anteriorButton.setEnabled(true);
        } else {
            JOptionPane.showMessageDialog(this, "Não foi encontrada nenhuma turma com o critério especificado!", "Pesquisa de turma", JOptionPane.WARNING_MESSAGE);
            browseButtonActionPerformed(evt);
        }
    }

    private void carregaComboCursos(List<Curso> resultsCurso) {

        //Carrega todos os cursos
        cmbCurso.removeAllItems();
        for (Curso obj : resultsCurso) {
            cmbCurso.addItem(obj.getId() + " - " + obj.getDescricao());
        }
        cmbCurso.setSelectedIndex(-1);

    }

    private void carregaCurso(Curso obj) {
        cmbCurso.removeAllItems();
        cmbCurso.addItem(obj.getId() + " - " + obj.getDescricao());
    }

    private boolean validarCamposObrigatoriosInclusao() {

        if (disciplinaTextField.getText().length() == 0) { //Verifica se foi preenchido o campo DISCIPLINA
            JOptionPane.showMessageDialog(this, "DISCIPLINA deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (cmbCurso.getSelectedIndex() == -1) { //Verifica se foi preenchido o campo CURSO
            JOptionPane.showMessageDialog(this, "CURSO deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        return true;
    }

    private boolean validarCamposObrigatorios() {

        if (idTextField.getText().length() == 0) { //Verifica se foi preenchido o campo ID
            JOptionPane.showMessageDialog(this, "ID deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (disciplinaTextField.getText().length() == 0) { //Verifica se foi preenchido o campo DISCIPLINA
            JOptionPane.showMessageDialog(this, "DISCIPLINA deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (cmbCurso.getSelectedIndex() == -1) { //Verifica se foi preenchido o campo CURSO
            JOptionPane.showMessageDialog(this, "CURSO deve ser preenchido!", "Erro", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        return true;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
